<?php
/**
 * Created by PhpStorm.
 * User: timo
 * Date: 2020/3/28
 * Time: 13:04
 */
class Model_Api_Standard_Malls
{

    private static $_typeid = 21;


    /**
     * @desc 商品列表
     * @param $params
     * @return array
     */
    public static function search($params, $keyword, $currentpage, $pagesize = '10')
    {

        $sortType = intval($params['sorttype']);
        $attrId = $params['attrid'];
        $classify = $params['classify'];
        $page = $currentpage;
        $page = $page ? $page : 1;

        $where = ' WHERE a.ishidden=0 ';
        $value_arr = array();

        //排序
        $orderBy = "";
        if (!empty($sortType))
        {
            if ($sortType == 1)//价格升序
            {
                $orderBy = "  a.price ASC,";
            }
            else if ($sortType == 2) //价格降序
            {
                $orderBy = "  a.price DESC,";
            }
            else if ($sortType == 3) //销量降序
            {
                $orderBy = " sellnum DESC,";
            }
            else if ($sortType == 4)//推荐
            {
                $orderBy = " a.shownum DESC,";
            }
        }

        //关键词
        if (!empty($keyword))
        {
            $where .= " AND a.title like :keyword ";
            $value_arr[':keyword'] = '%' . $keyword . '%';
        }
        //按属性
        if (!empty($attrId))
        {
            $where .= Product::get_attr_where($attrId);
        }

        //按分类
        if (!empty($classify))
        {
            $where .= Model_Api_Standard_Malls::get_classify_where($classify);
        }

        $offset = (intval($page) - 1) * $pagesize;
        //查询真实购买量
        $sell_where = " LEFT JOIN (SELECT COUNT(*) as s_num,productautoid FROM `sline_member_order` WHERE typeid=".self::$_typeid." GROUP BY productautoid) AS s ON s.productautoid=a.id";
        $files = ",(IFNULL(a.bookcount,0)+IFNULL(s.s_num,0)) AS sellnum";
        //如果选择了目的地
        if (!empty($destId))
        {
            $sql = "SELECT a.*{$files} FROM `sline_malls` a ";
            $sql .= "LEFT JOIN `sline_kindorderlist` b ";
            $sql .= "ON (a.id=b.aid AND b.typeid=".self::$_typeid." AND a.webid=b.webid AND b.classid=$destId)";
            $sql .= $sell_where;
            $sql .= $where;
            $sql .= "ORDER BY {$orderBy} IFNULL(b.displayorder,9999) ASC,a.modtime DESC,a.addtime DESC ";
        }
        else
        {
            $sql = "SELECT a.*{$files} FROM `sline_malls` a ";
            $sql .= "LEFT JOIN `sline_allorderlist` b ";
            $sql .= "ON (a.id=b.aid AND b.typeid=".self::$_typeid." AND a.webid=b.webid)";
            $sql .= $sell_where;
            $sql .= $where;
            $sql .= "ORDER BY {$orderBy} IFNULL(b.displayorder,9999) ASC,a.modtime DESC,a.addtime DESC ";
        }

        //计算总数
        $totalSql = "SELECT count(*) as dd " . strchr($sql, " FROM");
        $totalSql = str_replace(strchr($totalSql, "ORDER BY"), '', $totalSql);//去掉order by

        $totalN = DB::query(1, $totalSql)->parameters($value_arr)->execute()->as_array();
        $totalNum = $totalN[0]['dd'] ? $totalN[0]['dd'] : 0;

        $sql .= "LIMIT {$offset},{$pagesize}";
        $arr = DB::query(1, $sql)->parameters($value_arr)->execute()->as_array();
        foreach ($arr as &$v)
        {
            $v['commentnum'] = Model_Comment::get_comment_num($v['id'], self::$_typeid); //评论次数
            $v['score'] = $v['satisfyscore'] . '%';
            $v['price'] = self::get_minprice($v['id'], $v);//最低价
            $v['attrlist'] = self::get_attr_list($v['attrid'], self::$_typeid);//属性列表.
            $v['iconlist'] = Product::get_ico_list($v['iconlist']);
            if (Model_Supplier::display_is_open() && $v['supplierlist'])
            {
                $v['suppliername'] = Arr::get(Model_Supplier::get_supplier_info($v['supplierlist'], array('suppliername')), 'suppliername');
            }

            $v['litpic'] = Common::img($v['litpic'],260,176);
            $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);
        }
        $out = array(
            'total' => $totalNum,
            'list' => $arr,
            'is_finished'=>count($arr)<$pagesize?true:false //是否还有更多的数据
        );
        return $out;
    }

    /**
     * @desc 商城详情
     * @param $id
     * @return array
     */
    public static function detail($params)
    {
        if($params['id'])
        {
            $id = $params['id'];
            $userid = $params['userid'];

            $info = DB::select()->from('malls')->where('id', '=', $id)->execute()->current();
            //seo
            $seo_info = Product::seo($info);

            $info['seo_info'] = $seo_info;
            //产品图片
            $piclist = Product::pic_list($info['piclist']);
            $p = array();
            foreach ($piclist as &$pic)
            {
                $pi = Model_Api_Standard_System::reorganized_resource_url($pic[0]);
                array_push($p, $pi);
            }

            $info['piclist'] = $p;
            //属性列表
            $info['attrlist'] = self::get_attr_list($info['attrid']);

            //点评数
            $info['commentnum'] = Model_Comment::get_comment_num($info['id'], self::$_typeid);
            //销售数量
            $info['sellnum'] = Model_Member_Order::get_sell_num($info['id'], self::$_typeid) + intval($info['bookcount']);
            //产品编号
            $info['series'] = St_Product::product_series($info['id'], self::$_typeid);
            //产品图标
            $info['iconlist'] = Product::get_ico_list($info['iconlist']);
            //行程附件
            $info['linedoc'] = unserialize($info['linedoc']);
            //满意度
            $info['score'] = St_Functions::get_satisfy(self::$_typeid, $info['id'], $info['satisfyscore']);

            $info['litpic'] = Common::img($info['litpic'],750,750);
            $info['litpic'] = Model_Api_Standard_System::reorganized_resource_url($info['litpic']);

            $info['basehost'] = $GLOBALS['cfg_basehost'];

            //扩展字段信息
            $extend_info = self::extend($info['id'], self::$_typeid);
            $info['extend_info'] = $extend_info;

            //套餐信息
            $info['suit_info'] = self::suit($info['id']);

            $params = array(
                'typeid'        => self::$_typeid,
                'productinfo'   => $info,
                'onlyrealfield' => 1,
                'pc'            => 0,
            );
            $info['detail_list'] = self::get_content($params);

            // 更加ID查询可用的优惠券
            if(St_Functions::is_normal_app_install('coupon'))
            {
                $info['coupon_list'] = Model_Coupon::get_product_coupon_list($info['id'],self::$_typeid);
            }

            //分销赚取的金额
            if(St_Functions::is_normal_app_install('mobiledistribution'))
            {
                if(!empty($userid))
                {
                    $fenxiao = DB::select()->from('fenxiao')->where("memberid",'=',$userid)->execute()->current();
                    $fxgroupid = DB::select('fxgroupid')->from('fenxiao')->where("memberid",'=',$userid)->execute()->current();
                    $commission_type = Model_Fenxiao_Config::get_val('cfg_fenxiao_commission_type_'.$params['typeid'],$fxgroupid['fxgroupid']);
                    if($commission_type==1)
                    {
                        $commission_rate = Model_Fenxiao::get_commission_rate($params['typeid'],$info['id'],$fxgroupid['fxgroupid']);
                        $v['commission'] =$commission_rate[0]*100;
                        $v['commission'] = empty($v['commission'])?0:$v['commission'];
                        $v['commission'] .='%';
                        $v['profit'] = $info['price']*$commission_rate[0];
                    }
                    else if($commission_type==2)
                    {
                        $commission_rate = Model_Fenxiao::get_commission_rate_platform($params['typeid'],$info['id'],$fxgroupid['fxgroupid']);
                        $v['commission'] =$commission_rate[0]*100;
                        $v['commission'] = empty($v['commission'])?0:$v['commission'];
                        $v['commission'] .='%';
                        $temp_order = array('typeid'=>$params['typeid'],'productautoid'=>$info['id'],'totalprice'=>$info['price'],'dingnum'=>1);
                        $platform_price = Model_Member_Order_Compute::caculate_platform_commission($temp_order);
                        $platform_price = $platform_price==0? $info['price']:$platform_price;
                        $v['profit'] = $platform_price*$commission_rate[0];
                    }
                    else
                    {
                        $commission_cash = Model_Fenxiao::get_commission_cash_line($params['typeid'],$info['id'],$fxgroupid['fxgroupid']);
                        $v['commission'] = $commission_cash[0]['adult'];
                        $v['commission'] = empty($v['commission'])?0:$v['commission'];
                        $v['profit'] = $v['commission'];
                    }
                    $info['profit'] = $v['profit'];
                    $info['is_fenxiao'] = !empty($fenxiao) && $fenxiao['status']==1?true:false;
                }
            }
            return $info;
        } else
        {
            return array();
        }
    }


    /**
     * 获取线路套餐列表
     * @param $productid
     * @return Array
     */
    public static function suit($productid)
    {
        $pay_name = array(
            '1' => '全款支付',
            '2' => '定金支付',
            '3' => '二次确认',
        );

        $suit = DB::select()->from('malls_suit')
            ->where('productid', '=', $productid)
            ->order_by('displayorder', 'ASC')
            ->execute()
            ->as_array();
        foreach ($suit as &$r)
        {
            $r['title'] = $r['suitname'];
            $r['litpic'] = Common::img($r['litpic'],200,200);
            $r['litpic'] = Model_Api_Standard_System::reorganized_resource_url($r['litpic']);
            $r['paytype_name'] = $pay_name[$r['paytype']];
        }

        return $suit;
    }

    /**
     * @function 获取详细行程内容
     * @param $params
     * @return array
     */
    public static function get_content($params)
    {
        $default=array(
            'typeid'=>'',
            'productinfo'=>0,
            'onlyrealfield'=>0,
            'pc'=>0

        );

        $params=array_merge($default,$params);
        extract($params);

        $table ='sline_malls_content';
        $extend_tables = 'sline_malls_extend_field';
        $where = '';

        $sql = "SELECT columnname,chinesename,isrealfield FROM {$table} ";

        $sql.= "WHERE webid=0 and isopen=1 ";

        $sql.= "ORDER BY displayorder ASC";
        $arr = DB::query(1,$sql)->execute()->as_array();

        //扩展表数据
        $productid = $productinfo['id'];//产品id
        $sql = "SELECT * FROM $extend_tables WHERE productid='$productid'";
        $ar = DB::query(1,$sql)->execute()->as_array();
        $list = array();
        foreach($arr as $v)
        {
            if ($v['columnname'] == 'tupian')
            {
                continue;
            }
            $content = !empty($productinfo[$v['columnname']]) ? $productinfo[$v['columnname']] : $ar[0][$v['columnname']];
            $content = $content ? $content : '';

            if(empty($content)) continue;

            $a = array();
            $a['columnname'] = $v['columnname'];
            $a['chinesename'] = $v['chinesename'];

            $a['content'] = Model_Api_Standard_Xcx::filter_content($content);
            $list[] = $a;

        }
        return $list;
    }

    /**
     * 检查商品是否可以下单
     */
    public static function check_malls_order($productid,$suit_id,$num,$userid,$type = 2)
    {

        if(!$productid || !$suit_id)
        {
            return array('status'=> false,'msg'=> '提交信息有误');
        }
        if($num == -1 || $num >= 1)
        {

        }
        else
        {
            return array('status'=> false,'msg'=> '请选择数量');
        }
        $info = DB::select()->from("malls")->where("id","=",$productid)->and_where("status","=",3)->execute()->current();
        if(!$info)
        {
            return array('status'=> false,'msg'=> '商品不存在或已下架');
        }

        $suit_info = DB::select()->from("malls_suit")->where("id","=",$suit_id)->execute()->current();
        if(!$suit_info)
        {
            return array('status'=> false,'msg'=> '商品不存在或已下架');
        }

        if($type == 2)
        {
            // 库存数量
            $res = DB::select()->from("malls_cars")
                ->where("malls_id", "=", $productid)
                ->and_where("suit_id", "=", $suit_id)
                ->and_where("mid", "=", $userid)
                ->and_where("type", "=", 2)
                ->execute()
                ->current();
            if($res)
            {
                $num = $res['num'] + $num;
            }
        }


        if($num == 0)
        {
            return array('status'=> false,'msg'=> '数量不能为0');
        }

        if($suit_info['number'] != -1)
        {
            if($num > $suit_info['number'])
            {
                return array('status'=> false,'msg'=> '已超出库存');
            }
        }

        // 限购数量
        if($suit_info['max_number'] != -1)
        {
            if($num > $suit_info['max_number'])
            {
                return array('status'=> false,'msg'=> '已超出限购数量');
            }
        }
        $info['litpic'] = $suit_info['litpic'];
        return array('status'=> true,'info'=>$info,'num'=>$num);

    }


    /**
     * 检查购物数据
     * @param $productid
     * @param $suit_id
     * @param $num
     * @return array
     */
    public static function check_malls_car($productid,$suit_id,$num)
    {

        $info = DB::select()->from("malls")->where("id","=",$productid)->and_where("status","=",3)->execute()->current();
        if(!$info)
        {
            return array('status'=> 201,'msg'=> '商品不存在或已下架');
        }

        $suit_info = DB::select()->from("malls_suit")->where("id","=",$suit_id)->execute()->current();
        if(!$suit_info)
        {
            return array('status'=> 201,'msg'=> '商品不存在或已下架');
        }

        // 限购数量
        if($suit_info['max_number'] != -1)
        {
            if($num > $suit_info['max_number'])
            {
                return array('status'=> 202,'msg'=> '已超出限购数量','num'=>$suit_info['max_number'],'price'=> $suit_info['price'],'suit_name'=> $suit_info['suitname']);
            }
        }

        if($suit_info['number'] != -1)
        {
            if($num > $suit_info['number'])
            {
                return array('status'=> 202,'msg'=> '已超出库存','num'=>$suit_info['number'],'price'=> $suit_info['price'],'suit_name'=> $suit_info['suitname']);
            }
        }

        return array('status'=> 200,'price'=> $suit_info['price'],'suit_name'=> $suit_info['suitname'],'suit_info'=> $suit_info);

    }


    /**
     * @function 判断库存
     * @param $dingnum 预订数量
     * @param string $suitid 套餐ID
     * @param string $usedate 使用日期，格式为2016-01-01
     * @param string $enddate 结束日期，格式为2016-01-01
     * @param array $extraparam 附加参数
     * @return bool
     */
    public static function check_storage($dingnum, $suitid = '')
    {
        if (empty($suitid))
        {
            return false;
        }
        $query = DB::select('number', 'id','max_number')->from('malls_suit')
            ->and_where('id', '=', $suitid);
        $row = $query->execute()->current();
        $status = true;
        if (empty($row) || empty($row['id']))
        {
            $status = false;
        }
        else if ($row['number'] != '-1' && intval($row['number']) < intval($dingnum))
        {
            $status = false;
        }
        else if($row['max_number'] != '-1' && intval($row['max_number']) < intval($dingnum))
        {
            $status = false;
        }
        return $status;
    }

    /**
     * @function 获取订单列表
     * @param $param
     */
    public static function get_order_list($params)
    {
        $status = $params['status'];
        $page = $params['page'] ? $params['page'] : 1;
        $limit = $params['pagesize'] ? $params['pagesize'] : 10;
        $start = (intval($page) - 1) * $limit;
        $memberid = $params['userid'];

        $order = 'order by a.addtime desc';
        if (!empty($sort)) {
            $order = " order by a.{$sort['property']} {$sort['direction']},a.addtime desc";
        }

        $w = "where a.id>0 and a.pid=0 and a.typeid=21 ";


        if (!empty($memberid) || $memberid === 0 || $memberid === '0') {
            $w .= ' and a.memberid=' . $memberid;
        }

        $w .= " and b.is_virtual!=2";
        $sql = "SELECT a.* FROM `sline_member_order` AS a
        LEFT JOIN `sline_member` AS b ON(a.memberid=b.mid)
        $w GROUP BY a.ordersn  $order";

        $sql .= " LIMIT $start,$limit";

        $list = DB::query(Database::SELECT, $sql)->execute()->as_array();
        $new_list = array();
        foreach ($list as $k => $v) {

            $pinyin = DB::select('maintable')->from('model')->where('id','=',$v['typeid'])->execute()->get('maintable');
            $id = DB::select('id')->from($pinyin)->where('id','=',$v['productautoid'])->execute()->get('id');
            if(!empty($id))
            {
                $v['addtime'] = date('Y-m-d H:i:s', $v['addtime']);
                $v['price']   = Model_Malls_Order::order_total_payprice($v['id'], $v);
                $v['statusname'] = Model_Malls_Order::$orderStatus['status'];
                $v['dingnum']    = $v['dingnum'] + $v['childnum'] + $v['oldnum']+$v['people4_num']+$v['people5_num']+$v['people6_num'];

                //订单总价信息
                $total_info = Model_Member_Order_Compute::get_order_price($v['id']);
                if($total_info && !empty($total_info['total_price']))
                {
                    $v['price'] = $total_info['pay_price'];
                }

                $v['litpic'] = Common::img($v['litpic']);
                $v['litpic'] = Model_Api_Standard_System::reorganized_resource_url($v['litpic']);

                $new_list[] = $v;
            }
        }
        return $new_list;
    }


    /*
     *分类生成where条件,用于多条件分类搜索.
     */
    public static function get_classify_where($classify)
    {
        $arr = Common::remove_arr_empty(explode('_', $classify));
        $str = " and (";
        foreach ($arr as $k => $value)
        {
            $value = intval($value);
            if ($value != 0)
            {
                $str .= $k > 0 ? " or" : '';
                $str .= " FIND_IN_SET($value,a.classify) ";
            }
        }
        $str .=")";
        return $str;
    }


    // 获取运费
    public static function get_express_fee($param)
    {
        $userid = $param['userid'];
        $car_id = $param['car_id'];
        $addressid = $param['addressid'];

        // 循环检查
        $res  = DB::query(1,"select * from sline_malls_cars WHERE mid={$userid} and id in ({$car_id})")->execute()->as_array();
        $total_price = 0;
        foreach ($res as $v)
        {
            $suit_info = DB::select()->from('malls_suit')->where('id','=',$v['suit_id'])->execute()->current();
            $freightid = $suit_info['freightid'];
            $plan_result = null;
            $plan_result = Model_Express_Plan::get_plan($freightid, $addressid);
            if($plan_result['status']==0)
            {
                return array('status'=>false);
            }
            $price = Model_Express_Plan::get_freight_price($suit_info,$plan_result['data'],$v['num']);
            $total_price = $total_price + floatval($price);
        }
        return array('status'=>true,'price'=>$price);
    }

    /**
     * @function 获取产品最低价
     * @param $productid
     * @param array $params
     * @return number
     */
    public static function get_minprice($productid, $params = array())
    {
        $time = strtotime(date('Y-m-d'));
        $update_minprice = false;
        if (!is_array($params))
        {
            $params = array('suitid' => $params);
        }
        if (!isset($params['suitid']))
        {
            if (!isset($params['info']))
            {
                $params['info'] = DB::select()->from('malls')->where('id', '=', $productid)->execute()->current();
            }
            if ($params['info']['price_date'] == $time)
            {
                return Currency_Tool::price($params['info']['price']);
            }
            //更新最低价
            $update_minprice = true;
        }
        $where = isset($params['suitid']) ? " AND id=" . $params['suitid'] : '';
        $sql = 'SELECT MIN(price) AS price FROM `sline_malls_suit` WHERE productid=' . $productid . ' and price>0 and (number>0 or number=-1)' . $where;
        $row = DB::query(1, $sql)->execute()->current();
        $price = !empty($row) ? $row['price'] : 0;
        if ($update_minprice)
        {
            DB::update('malls')->set(array('price' => $price, 'price_date' => $time))->where('id', '=', $productid)->execute();
        }
        return Currency_Tool::price($price);
    }
    /**
     * @function 根据属性id返回属性数组.
     * @param $attrid
     * @return mixed
     */
    public static function get_attr_list($attrid,$typeid=null)
    {
        if(empty($attrid))return array();
        $sql = "SELECT id,attrname FROM `sline_malls_attr` WHERE id IN($attrid) AND isopen=1 AND pid!=0  ORDER BY displayorder ASC";
        $arr = DB::query(1,$sql)->execute()->as_array();
        return $arr;
    }

    /**
     * @function 获取产品属性名称数组
     * @param $attrid
     * @return array
     */
    public static function product_attr($attrid, $typeid=null)
    {
        if (empty($attrid))
        {
            return;
        }
        $attrid = trim($attrid, ',');
        $attrid_arr = explode(',', $attrid);
        $arr = DB::select('attrname')->from('malls_attr')->where('id', 'in', $attrid_arr)->and_where('pid', '!=', 0)->execute()->as_array();
        return $arr;
    }

    /**
     * @function 获取扩展字段
     * @param $productid
     * @param $typeid
     * @return mixed
     */
    public static function extend($productid, $typeid=null)
    {
        $sql = "SELECT * FROM sline_malls_extend_field ";
        $sql .= "WHERE productid={$productid}";
        $arr = DB::query(1, $sql)->execute()->as_array();
        return $arr;

    }


    /**
     * @function 获取套餐信息
     * @param $suitid
     * @return array
     */
    public static function suit_info($suitid)
    {
        $suitInfo = DB::select()->from('malls_suit')->where('id', '=', $suitid)->execute()->current();
        if(empty($suitInfo))
        {
            return null;
        }
        $suitInfo['sellprice'] = Currency_Tool::price($suitInfo['sellprice']);
        $suitInfo['price'] = Currency_Tool::price($suitInfo['price']);
        $suitInfo['dingjin'] = 0;
        $suitInfo['achieve_price'] = 0;
        return $suitInfo;
    }

}